import { Directive, DirectiveBinding } from 'vue'
 
interface ExHTMLElement extends HTMLElement {
  resizeListener: EventListener
}
 
export const tableHeight: Directive = {
  mounted: (el: ExHTMLElement, binding: DirectiveBinding) => {
    el.resizeListener = () => {
      setHeight(el, binding)
    }
    setHeight(el, binding)
    window.addEventListener('resize', el.resizeListener)
  },
  unmounted(el: ExHTMLElement) {
    window.removeEventListener('resize', el.resizeListener)
  },
  updated(el: ExHTMLElement, binding: DirectiveBinding) {
    setHeight(el, binding)
  }
}
 
function setHeight(el: ExHTMLElement, binding: DirectiveBinding) {
  const rect = el.getBoundingClientRect()
  const rectTop = rect.top + window.pageYOffset
  const bottom = binding?.value?.bottom || 16
  const pageHeight = window.innerHeight
  el.style.height = pageHeight - rectTop - bottom + 'px'
  el.style.overflowY = 'auto'  
}
 
